//
//  FindPasswordViewController.m
//  wanhucang
//
//  Created by 郝志宇 on 16/1/27.
//  Copyright © 2016年 XuDong Jin. All rights reserved.
//

#import "FindPasswordViewController.h"
#import "IGCommonApi.h"
#import "IGForgetPasswordApi.h"
#import "IGPwdTextField.h"
#import "IGCaptchaView.h"

@interface FindPasswordViewController () <UITableViewDataSource, UITableViewDelegate> {
    NSString *phonnum;
    NSString *vertnum;
    NSString *passone;
    NSString *passtwo;
    
    UIButton *identBtn;
    UIButton *confirmBtn;
    
    NSInteger  timer;
}
@property (nonatomic, strong) IGCommonApi *commonApi;

@end

@implementation FindPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    self.title = @"忘记密码";
    self.title = NSLocalizedString(@"Forget Password", nil);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidTakeScreenshot) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
    
    self.table.backgroundColor =  [UIColor c2Color];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 130)];
    UIButton *submit = [UIButton buttonWithType:UIButtonTypeCustom];
    submit.layer.cornerRadius = 20.f;
    submit.layer.masksToBounds = YES;
    submit.frame = CGRectMake(0, 0, GSCALE(300), GSCALE(44));
    submit.titleLabel.font = [UIFont font16];
    [submit setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [submit setBackgroundColor:[UIColor appColor]];
//    [submit setTitle:@"确定重置" forState:UIControlStateNormal];
    [submit setTitle:NSLocalizedString(@"Confirm to reset", nil) forState:UIControlStateNormal];
    [submit addTarget:self action:@selector(submitAction:) forControlEvents:UIControlEventTouchUpInside];
    submit.center = CGPointMake(view.width/2, submit.height/2+40);
    confirmBtn=submit;
    [view addSubview:submit];
    self.table.tableFooterView = view;
    
    self.table.contentInset = UIEdgeInsetsMake(10, 0, 0, 0);
}

#pragma mark - UITableViewDataSource, UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    CGFloat x = cell.separatorInset.left;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UITextField *textView = [[UITextField alloc] initWithFrame:CGRectMake(x, 0, KSCREENWIDTH-2*x, 50)];
    if (indexPath.row==0) {
        textView.text = phonnum;
        textView.keyboardType = UIKeyboardTypePhonePad;
        UILabel *left = [[UILabel alloc] initWithFrame:CGRectZero];
//        left.text = @"手机号";
        left.text = NSLocalizedString(@"Mobile Number", nil);
        left.font = [UIFont font16];
        left.textColor=[UIColor c4Color];
        [left sizeToFit];
        left.width += 20;
        textView.leftView = left;
        
        UILabel *right = [[UILabel alloc] initWithFrame:CGRectZero];
//        right.text = @"输入手机号码";
        right.text = NSLocalizedString(@"Mobile Number", nil);
        right.textColor=[UIColor c5Color];
        right.textAlignment=NSTextAlignmentRight;
        right.font = [UIFont font16];
        [right sizeToFit];
        right.width += 20;
        textView.rightView = right;
        [cell.contentView addSubview:textView];
    }
    if (indexPath.row==1) {
        textView.size=CGSizeMake(KSCREENWIDTH-2*x-96, 50);
        textView.text = vertnum;
        textView.keyboardType = UIKeyboardTypePhonePad;
        UILabel *left = [[UILabel alloc] initWithFrame:CGRectZero];
        left.text = NSLocalizedString(@"Verification Code", nil);
        left.font = [UIFont font16];
        left.textColor=[UIColor c4Color];
        [left sizeToFit];
        left.width +=20;
        textView.leftView = left;
        UILabel *right = [[UILabel alloc] initWithFrame:CGRectZero];
        right.text = NSLocalizedString(@"SMS Code", nil);
        right.textColor=[UIColor c5Color];
        right.textAlignment=NSTextAlignmentRight;
        right.font = [UIFont font16];
        [right sizeToFit];
        right.width += 20;
        textView.rightView = right;
        [cell.contentView addSubview:textView];
        
        UIButton *identyBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        [identyBtn setTitle:NSLocalizedString(@"Acquire", nil) forState:UIControlStateNormal ];
        [identyBtn setTitleColor:[UIColor c5Color] forState:UIControlStateDisabled];
        [identyBtn setTitleColor:[UIColor appColor] forState:UIControlStateNormal];
        [identyBtn addTarget:self action:@selector(getverCode) forControlEvents:UIControlEventTouchUpInside];
        identyBtn.enabled=YES;
        identyBtn.titleLabel.font=[UIFont font16];
        identyBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [identyBtn sizeToFit];
        identBtn=identyBtn;
        identyBtn.centerY=textView.centerY;
        identyBtn.x=KSCREENWIDTH-x-identyBtn.width;
        [cell.contentView addSubview:identyBtn];
        
        
        UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, KSCREENWIDTH, .5)];
        line.backgroundColor = [UIColor lightGrayColor];
        [cell.contentView addSubview:line];
    }
    if (indexPath.row==2) {
        textView = [[IGPwdTextField alloc] initWithFrame:CGRectMake(x, 0, KSCREENWIDTH-2*x, 50)];
        textView.text =passone;
        textView.keyboardType = UIKeyboardTypeAlphabet;
        textView.secureTextEntry = YES;
        UILabel *left = [[UILabel alloc] initWithFrame:CGRectZero];
//        left.text = @"新密码";
        left.text = NSLocalizedString(@"New Password", nil);
        left.font = [UIFont font16];
        left.textColor=[UIColor c4Color];
        [left sizeToFit];
        left.width += 20;
        textView.leftView = left;
        UILabel *right = [[UILabel alloc] initWithFrame:CGRectZero];
//        right.text = @"6-16位数字或字母";
        right.text = NSLocalizedString(@"6-16 Digits or Characters", nil);
        right.textColor=[UIColor c5Color];
        right.textAlignment=NSTextAlignmentRight;
        right.font = [UIFont font16];
        [right sizeToFit];
        right.width += 20;
        textView.rightView = right;
        [cell.contentView addSubview:textView];
        
        UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, KSCREENWIDTH, .5)];
        line.backgroundColor = [UIColor lightGrayColor];
        [cell.contentView addSubview:line];
    }
    if (indexPath.row==3) {
        textView = [[IGPwdTextField alloc] initWithFrame:CGRectMake(x, 0, KSCREENWIDTH-2*x, 50)];
        textView.text = passtwo;
        textView.keyboardType = UIKeyboardTypeAlphabet;
        textView.secureTextEntry = YES;
        UILabel *left = [[UILabel alloc] initWithFrame:CGRectZero];
//        left.text = @"确认密码";
        left.text = NSLocalizedString(@"Confirm Password", nil);
        left.font = [UIFont font16];
        left.textColor=[UIColor c4Color];
        [left sizeToFit];
        left.width += 8;
        textView.leftView = left;
        
        UILabel *right = [[UILabel alloc] initWithFrame:CGRectZero];
//        right.text = @"再次输入密码";
        right.text = NSLocalizedString(@"Password Again", nil);
        right.textColor=[UIColor c5Color];
        right.textAlignment=NSTextAlignmentRight;
        right.font = [UIFont font16];
        [right sizeToFit];
        right.width += 20;
        textView.rightView = right;
        [cell.contentView addSubview:textView];
        
        UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, KSCREENWIDTH, .5)];
        line.backgroundColor = [UIColor lightGrayColor];
        [cell.contentView addSubview:line];
    }
    textView.borderStyle = UITextBorderStyleNone;
    textView.leftViewMode = UITextFieldViewModeAlways;
    textView.rightViewMode=UITextFieldViewModeUnlessEditing;
    textView.font = [UIFont font16];
    textView.clearButtonMode = UITextFieldViewModeWhileEditing;
    [textView addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    [textView addTarget:self action:@selector(textBeainEditing:) forControlEvents:UIControlEventEditingDidBegin];
    [textView addTarget:self action:@selector(textEndEditing:) forControlEvents:UIControlEventEditingDidEnd];
    textView.tag = indexPath.row;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 50;
}

- (void)submitAction:(UIButton *)btn {
    [self.view endEditing:YES];
    if (phonnum.length==0){
//        [self presentMessageTips:@"请输入手机号"];
        [self presentMessageTips:NSLocalizedString(@"Please Input Mobile Number", nil)];
        return;
    }else if (![phonnum isTelephone]) {
//        [self presentMessageTips:@"请输入正确的手机号"];
        [self presentMessageTips:NSLocalizedString(@"Please Input Correct Mobile No.", nil)];
        return;
    } else {
        if (vertnum.length==0) {
            [self presentMessageTips:NSLocalizedString(@"Please Input Verification Code", nil)];
            return;
        } else {
            if (passone.length==0) {
                [self presentMessageTips:NSLocalizedString(@"Please input password", nil)];
                return;
            }else if (passone.length<6||passone.length>16) {
                [self presentMessageTips:NSLocalizedString(@"Please Input 6-16 Digits or Characters", nil)];
                return;
            } else {
                if (passtwo.length==0){
                    [self presentMessageTips:NSLocalizedString(@"Password cannot be null, please re-enter the password.", nil)];
                    return;
                } else if(![passone isEqualToString:passtwo]) {
                    [self presentMessageTips:NSLocalizedString(@"Password not match,please confirm", nil)];
                    return;
                }
            }
        }
    }
    
    IGForgetPasswordApi *forgetApi = [[IGForgetPasswordApi alloc] initWithUsername:phonnum password:passone smsCode:vertnum];
    __weak typeof(self) weakSelf = self;
    [forgetApi startWithDecodeClass:[IGForgetPasswordResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            [weakSelf presentMessageTips:NSLocalizedString(@"Change Successfully", nil)];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    }];
}

- (void)textBeainEditing:(UITextField *)textView {
    self.table.bounces = YES;
}

- (void)textEndEditing:(UITextField *)textView {
    self.table.bounces = NO;
    if ([phonnum isTelephone]) {
        identBtn.enabled=YES;
    }
    if(textView.text.length!=0){
        textView.rightViewMode=UITextFieldViewModeNever;
    }else{
        textView.rightViewMode=UITextFieldViewModeUnlessEditing;
    }
    
}

- (void)textChange:(UITextField *)textView {
    if (textView.tag == 0) {
        //手机号
        if (textView.text.length>11) {
            textView.text = [textView.text substringToIndex:11];
        }
        phonnum = textView.text;
    }
    if (textView.tag == 1) {  //  验证码
        vertnum = textView.text;
    }
    if (textView.tag == 2) {
        if (textView.text.length>16) {
            textView.text = [textView.text substringToIndex:16];
        }
        passone = textView.text;
    }
    if (textView.tag == 3) {
        if (textView.text.length>16) {
            textView.text = [textView.text substringToIndex:16];
        }
        passtwo = textView.text;
    }
    
    
}

- (void)getverCode{
    [self.view endEditing:YES];
    if (phonnum.length==0) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Mobile Number", nil)];
        return;
    } else if (![phonnum isTelephone]) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Correct Mobile No.", nil)];
        return;
    }
    __weak typeof(self) weakSelf = self;
    [IGCaptchaView num:phonnum showCaptcha:^(NSString *cap) {
        [weakSelf getRealCode:cap];
    }];
}

- (void)getRealCode:(NSString *)code {
    [self showText:NSLocalizedString(@"Sending...", nil)];
    if (phonnum.length==0) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Mobile Number", nil)];
        return;
    } else if (![phonnum isTelephone]) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Correct Mobile No.", nil)];
        return;
    }

    timer = 60;
    self.commonApi = [[IGCommonApi alloc] init];
    self.commonApi.apiType = IGiGalleryApiTypeMemberFindPwdGetPhoneSMSNew;
    self.commonApi.phone = phonnum;
    self.commonApi.code = code;
    __weak typeof(self) weakSelf = self;
    [self.commonApi startWithDecodeClass:[IGCommonResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
//                [weakSelf presentMessageTips:@"发送成功"];
                [weakSelf presentMessageTips:NSLocalizedString(@"Sent Successfully", nil)];
                identBtn.userInteractionEnabled = NO;
//                NSString *title = [NSString stringWithFormat:@"%@s重发", @(timer)];
                NSString *title = [NSString stringWithFormat:@"%@ sec", @(timer)];
                [identBtn setTitle:title forState:UIControlStateNormal];
                [identBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                
                [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerDown:) userInfo:identBtn repeats:YES];
            });
        }
    }];
}

- (void)timerDown:(NSTimer *)time {
    timer--;
//    NSString *title = [NSString stringWithFormat:@"%@s重发", @(timer)];
    NSString *title = [NSString stringWithFormat:@"%@ sec", @(timer)];
    [identBtn setTitle:title forState:UIControlStateNormal];
    [identBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    if (timer == 0) {
        identBtn.userInteractionEnabled = YES;
        [identBtn setTitle:NSLocalizedString(@"Acquire", nil) forState:UIControlStateNormal];
        [identBtn setTitleColor:[UIColor appColor] forState:UIControlStateNormal];
        [time invalidate];
    }
}

- (void)userDidTakeScreenshot {
    [UIAlertView bk_showAlertViewWithTitle:@"" message:NSLocalizedString(@"You mobile screen is captured.\n Please pay attention to password security.", nil) cancelButtonTitle:NSLocalizedString(@"Confirm",nil) otherButtonTitles:nil handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
